#!/usr/bin/env python3

#==============================================================================
# Functionality
#==============================================================================
import pdb
import sys
import os
import re

# utility funcs, classes, etc go here.

def asserting(cond):
    if not cond:
        pdb.set_trace()
    assert(cond)

def has_stdin():
    return not sys.stdin.isatty()

def reg(pat, flags=0):
    return re.compile(pat, re.VERBOSE | flags)

#==============================================================================
# Cmdline
#==============================================================================
import argparse

parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, 
    description="""
TODO
""")
     
parser.add_argument('-v', '--verbose',
    action="store_true",
    help="verbose output" )
     
parser.add_argument('-i', '--ignore-case',
    dest='case', action="store_const", const='off',
    help="Match case insensitively" )
     
parser.add_argument('-s', '--case-sensitive',
    dest='case', action="store_const", const='on',
    help="Match case sensitively" )
     
parser.add_argument('-S', '--smart-case',
    dest='case', action="store_const", const='smart',
    help="Match case insensitively unless PATTERN contains uppercase characters" )

args = None

#==============================================================================
# Main
#==============================================================================

import narrow

def run():
    if args.verbose:
        print(args)
    if len(args.args) <= 0 and not has_stdin():
        # if there were no args and there was no input, prompt user.
        print('Enter input (press Ctrl-D when done):')

    exitcode = 1
    for line in sys.stdin:
        if narrow.narrow(line, args.args, case=args.case, verbose=args.verbose):
            print(line, end='')
            exitcode = 0
    sys.exit(exitcode)

def main():
    try:
        global args
        if not args:
            args, leftovers = parser.parse_known_args()
            args.args = leftovers
            if args.case == None:
                args.case = 'smart'
        return run()
    except IOError:
        # http://stackoverflow.com/questions/15793886/how-to-avoid-a-broken-pipe-error-when-printing-a-large-amount-of-formatted-data
        try:
            sys.stdout.close()
        except IOError:
            pass
        try:
            sys.stderr.close()
        except IOError:
            pass

if __name__ == "__main__":
    main()

